package yams.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import yams.common.IRepository;
import yams.common.exception.BreezeeException;
import yams.domain.ApartmentEntity;
import yams.domain.HouseEntity;
import yams.repository.IApartmentRepository;
import yams.repository.IHouseRepository;
import yams.service.IApartmentService;
import yams.service.IHouseService;
import yams.utils.SystemTool;

import java.util.ArrayList;
import java.util.List;

/**
 * 房间服务
 * Created by Luffy on 2017/06/06.
 */
@Service("houseService")
public class DefaultHouseService implements IHouseService {

    private final IHouseRepository houseRepository;
    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public DefaultHouseService(IHouseRepository houseRepository,
                               JdbcTemplate jdbcTemplate) {
        this.houseRepository = houseRepository;
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public IRepository<HouseEntity> getRepository() {
        return houseRepository;
    }

    @Override
    public void saveBeds(HouseEntity obj) {
        final String houseId = obj.getId();
        String delSql = "delete from T_BED where HOUSE_ID='" + houseId + "'";
        String insertSql = "insert into T_BED (PK_ID,CODE,BED_LENGTH,BED_TYPE,BED_WIDTH,HOUSE_ID,ROW_NUM) values(?,?,?,?,?,?,0)";
        List<Object[]> l = new ArrayList<>();
        if (obj.getBeds() != null) {
            obj.getBeds().forEach(bed -> {
                String id = SystemTool.uuid();
                l.add(new Object[]{id,id,bed.getBedLength(),bed.getBedType(),bed.getBedWidth(),houseId});
            });
        }
        jdbcTemplate.update(delSql);
        if (l.size() > 0)
            jdbcTemplate.batchUpdate(insertSql, l);
    }

    @Override
    public void saveDayPrice(HouseEntity obj) {
        final String houseId = obj.getId();
        String delSql = "delete from T_DAY_PRICE where HOUSE_ID='" + houseId + "'";
        String insertSql = "insert into T_DAY_PRICE (PK_ID,CODE,SHORT_RENT_TYPE,DAY_PRICE,HOUSE_ID,ROW_NUM) values(?,?,?,?,?,0)";
        List<Object[]> l = new ArrayList<>();
        if (obj.getDayPrices() != null) {
            obj.getDayPrices().forEach(dayPrice -> {
                String id = SystemTool.uuid();
                l.add(new Object[]{id,id,dayPrice.getShortRentType(),dayPrice.getDayPrice(),houseId});
            });
        }
        jdbcTemplate.update(delSql);
        if (l.size() > 0)
            jdbcTemplate.batchUpdate(insertSql, l);
    }

}
